<?php

/* --|	PHOTOS
  Software: Socially
  Version: 1.0
  Contact: http://socially.googlecode.com
  Info: http://socially.googlecode.com
  Support: http://socially.googlecode.com
  --------------------------------------------------------------------------
  Author: goker.cebeci | http://gokercebeci.com
  --------------------------------------------------------------------------
  License: Distributed under the GNU General Public License (GPL)
  http://www.gnu.org/licenses/gpl.html
  This program is distributed in the hope that it will be useful - WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE.
  ------------------------------------------------------------------------- */

class photos {

    private static $path = 'data/photos/';
    private static $profile = 'data/profile/';

    public static function _put($a) {
        $caption = $a['caption'] ? strip_tags($a['caption']) : $a['image']['name'];
        if ($a['profile']) {
            db::query(sprintf("UPDATE photos SET `isDefault` = 0 WHERE accountID = %d AND albumID = %d  AND `isDefault` = 1 LIMIT 1;", $a['ID'], $a['album']));
            db::query(sprintf("INSERT INTO photos
                    (accountID, albumID, caption, `isDefault`, `uploadDate`)
                    VALUES (%d,%d,'%s',1,NOW());"
                                    , $a['ID'], $a['album'], $caption));
        }
        return db::insertid();
    }

    public static function _get($a) {
        $gallery = db::query(sprintf("SELECT ID FROM photoGalleries WHERE UID = %d AND profile = 1 LIMIT 1;", $a['ID']), true);
        $photo = db::query(sprintf("SELECT ID FROM photo WHERE UID = %d AND GID = %d AND `default` = 1 LIMIT 1;", $a['ID'], $gallery->ID), true);
        return $photo->ID;
    }

    public static function _del($a) {
        db::query("DELETE FROM photos WHERE ID = $ID");
        @unlink($file);
    }

    public static function _resize($a) {
        if (move_uploaded_file($a['image']['tmp_name'], $a['file'])) {
            setlocale(LC_ALL, 'en_GB' . '.UTF-8');
            $img = new image($a['file']);
            if (($check = $img->check()) != 200)
                return common::result($check);
            $img->resize(self::$path . $a['album'] . '/' . image::name($a['imageID'] . 'normal'), 600, 600);
            $img->resize(self::$path . $a['album'] . '/' . image::name($a['imageID'] . 'thumb'), 100, 100, array('compress' => 90));
            if ($a['profile']) {
                $img->resize(self::$profile . $a['ID'] . '/' . image::name($a['ID'] . 'profile'), 200, 0);
                $img->resize(self::$profile . $a['ID'] . '/' . image::name($a['ID'] . 'thumb'), 100, 100, array('method' => 'crop', 'position' => 'top', 'compress' => 90));
                $img->resize(self::$profile . $a['ID'] . '/' . image::name($a['ID'] . 'mini'), 50, 50, array('method' => 'crop', 'position' => 'top', 'compress' => 90));
            }
            $img->kill();
            setlocale(LC_ALL, LOCALE);
            //@copy(self::$path.image::name($a['imageID'].'square').'.jpg',self::$profile.$a['ID'].image::name($a['ID'].'mini').'.jpg');
            if (is_file(self::$path . $a['album'] . '/' . image::name($a['imageID'] . 'normal') . '.jpg'))
                return true; else
                return false;
        } else
            return false;
    }

    public static function profile($a) {
        if ($a['random'])
            $r = db::query(sprintf("SELECT * FROM photos WHERE accountID = %d AND albumID = %d  AND ID <> %d ORDER BY ID DESC LIMIT 1;", $a['account'], $a['album'], $a['ID']), true);
        else
            $r = db::query(sprintf("SELECT * FROM photos WHERE ID = %d LIMIT 1;", $a['ID']), true);
        if ($r->ID) {
            self::changeDefault(array('account' => $r->accountID, 'album' => $r->albumID, 'ID' => $r->ID));
            setlocale(LC_ALL, 'en_GB' . '.UTF-8');
            $img = new image(self::$path . $r->albumID . '/' . image::name($r->ID . 'normal') . '.jpg');
            $img->resize(self::$profile . $r->accountID . '/' . image::name($r->accountID . 'profile'), 200, 0);
            $img->resize(self::$profile . $r->accountID . '/' . image::name($r->accountID . 'thumb'), 100, 100, array('method' => 'crop', 'position' => 'top', 'compress' => 90));
            $img->resize(self::$profile . $r->accountID . '/' . image::name($r->accountID . 'mini'), 50, 50, array('method' => 'crop', 'position' => 'top', 'compress' => 90));
            $img->kill();
            setlocale(LC_ALL, LOCALE);
        }
    }

    public static function get($a) {
        if ($a['owner']) {
            $r = db::query(sprintf("SELECT accountID FROM photos WHERE ID = %d LIMIT 1;", $a['ID']), true);
            return $r->accountID;
        }
        if ($a['photos']) {
            $r = db::query(sprintf("SELECT * FROM photosAlbum WHERE accountID = %d LIMIT 1;", $a['ID']), true, true);
            if ($r)
                foreach ($r as $k => $i) {
                    $r[$k]->thumb = db::query(sprintf("SELECT * FROM photos WHERE albumID = %d AND isDefault = 1 LIMIT 1;", $i->ID), true);
                    $r[$k]->thumb->src = $r[$k]->thumb->ID ? self::$path . $i->ID . '/' . image::name($r[$k]->thumb->ID . 'thumb') . '.jpg' : '/apps/profile/template/images/thumb.gif';
                }
        }
        if ($a['album']) {
            if (!$a['ID']) {
                $r = db::query(sprintf("SELECT ID FROM photosAlbum WHERE accountID = %d LIMIT 1;", $a['accountID']), true);
                $a['ID'] = $r->ID;
            }
            $r = db::query(sprintf("SELECT * FROM photosAlbum WHERE ID = %d LIMIT 1;", $a['ID']), true);
            $r->account = profile::get(array('ID' => $r->accountID));
            $r->photos = db::query(sprintf("SELECT * FROM photos WHERE albumID = %d ORDER BY ID DESC;", $r->ID), true, true);
            if ($r->photos)
                foreach ($r->photos as $k => $i) {
                    $r->photos[$k]->src = self::$path . $r->ID . '/' . image::name($i->ID . 'thumb') . '.jpg';
                }
        }
        if ($a['photo']) {
            $r = db::query(sprintf("SELECT a.ID as albumID,a.name,p.* FROM photosAlbum as a,photos as p
                        WHERE a.ID = p.albumID AND p.ID = %d LIMIT 1;", $a['ID']), true);
            $r->photos = db::query(sprintf("SELECT * FROM photos WHERE albumID = %d ORDER BY ID DESC;", $r->albumID), true, true);
            if ($r->accountID)
                $r->account = profile::get(array('ID' => $r->accountID));
            if ($r->photos)
                foreach ($r->photos as $k => $i) {
                    if ($i->ID == $a['ID'])
                        $point = $k;
                }
            $count = count($r->photos);
            if ($count) {
                $r->next = $r->photos[(($point + 1) % $count)]->ID;
                $r->prev = $r->photos[(($point == 0 ? $count - 1 : $point - 1) % $count)]->ID;
                $r->src = self::$path . $r->albumID . '/' . image::name($r->ID . 'normal') . '.jpg';
            }
        }
        if ($a['forcheck']) {
            $r = db::query("SELECT * FROM photos WHERE `checked` = 0 ORDER BY ID DESC LIMIT 1;", true);
            $r->account = profile::get(array('ID' => $r->accountID));
            $r->src = self::$path . $r->albumID . '/' . image::name($r->ID . 'normal') . '.jpg';
        }
        return $r;
    }

    public static function check() {
        $r = db::query(sprintf("SELECT COUNT(*) as total FROM photos WHERE accountID = %d LIMIT 1;", UID), true);
        return $r->total ? true : false;
    }

    // CREATE PHOTO ALBUM
    public static function create($a) {
        //db::query(sprintf("INSERT INTO photosAlbum (UID, profile) VALUES (%d,1);",$a['ID']));
        //$gallery = db::query(sprintf("SELECT ID FROM photosAlbum WHERE UID = %d AND profile = 1 LIMIT 1;",$a['ID']),true);
    }

    public static function album($a) {
        
    }

    // PROFILE ALBUM
    public static function profileAlbum($a) {
        $r = db::query(sprintf("SELECT ID FROM photosAlbum WHERE `accountID` = %d AND `isProfile` = 1 LIMIT 1;", $a['ID']), true);
        if (!$r->ID) {
            db::query(sprintf("INSERT INTO photosAlbum (`accountID`, `name`, `isProfile`, `createDate`)
                                        VALUES (%d,'%s',1,NOW());", $a['ID'], _('Profile Photos')));
            $r->ID = db::insertid();
        }
        @mkdir(self::$path . $r->ID);
        return $r->ID;
    }

    public static function limited($a) {
        $r = db::query(sprintf("SELECT COUNT(ID) as `limit` FROM photos WHERE accountID = %d AND albumID = %d;", $a['ID'], $a['album']), true);
        $limited = true;
        if (GOLD && PHOTOS_GOLD_LIMIT > $r->limit)
            $limited = false;
        if (SILVER && PHOTOS_SILVER_LIMIT > $r->limit)
            $limited = false;
        if (NORM && PHOTOS_NORM_LIMIT > $r->limit)
            $limited = false;
        return $limited;
    }

    public static function upload($a) {
        $ext = explode('.', $a['image']['name']);
        $ext = strtolower($ext[count($ext) - 1]);
        if (preg_match('/^(gif|png|jpe?g)$/', $ext)) {
            $a['album'] = self::profileAlbum($a);
            // CHECK LIMIT
            if (self::limited($a)) {
                return 600; /* echo 'tirt'; return common::result(600,_('limit full')); */
            }
            if ($a['album']) {
                $a['imageID'] = self::_put($a);
                @mkdir(self::$profile . $a['ID'] . '/');
                $a['file'] = self::$path . 'tmp.' . ($a['ID'] . @date('U')) . '.' . $ext;
                if (!self::_resize($a)) {
                    self::_del($a);
                    @unlink($a['file']);
                    return 800; /* common::result(601); */
                }
                @unlink($a['file']);
                return 200; //common::result(200);
            }
        } else
            return 800; //common::result(601);


    }

    public static function changeDefault($a) {
        db::query(sprintf("UPDATE photos SET `isDefault` = 0 WHERE accountID = %d AND albumID = %d  AND isDefault = 1 LIMIT 1;", $a['account'], $a['album']));
        db::query(sprintf("UPDATE photos SET `isDefault` = 1 WHERE accountID = %d AND albumID = %d  AND ID = %d LIMIT 1;", $a['account'], $a['album'], $a['ID']));
    }

    public static function delete($a) {
        $p = self::get(array('photo' => true, 'ID' => $a['ID']));
        if ($a['check']) {
            //notification mail
            $message = sprintf(_('Our moderation group did not approve your photo.') . '<br/><a href="http://' . DOMAIN . '/en/photos">http://' . DOMAIN . '/en/photos</a>');
            notification::mail(array('application' => 'postie', 'sender' => UID, 'recipient' => $p->accountID, 'message' => $message));
        }
        if ($p->isDefault) {
            @unlink(self::$profile . $p->accountID . '/' . image::name($p->accountID . 'profile') . '.jpg');
            @unlink(self::$profile . $p->accountID . '/' . image::name($p->accountID . 'thumb') . '.jpg');
            @unlink(self::$profile . $p->accountID . '/' . image::name($p->accountID . 'mini') . '.jpg');
            self::profile(array('account' => $p->accountID, 'album' => $p->albumID, 'ID' => $p->ID, 'random' => true));
            @cache::del(array("profile[" . $p->accountID . "]", "profile[" . (account::getusername($p->accountID)) . "]"));
        }
        db::query(sprintf("DELETE FROM photos WHERE ID = %d AND accountID = %d LIMIT 1", $p->ID, $p->accountID));
        @unlink(self::$path . $p->albumID . '/' . image::name($p->ID . 'normal') . '.jpg');
        @unlink(self::$path . $p->albumID . '/' . image::name($p->ID . 'thumb') . '.jpg');
        return common::result(200);
    }

    public static function approve($ID) {
        db::query(sprintf("UPDATE photos SET `checked` = 1 WHERE `ID` = '%d';", $ID));
        return common::result(200, _('The photo approved'));
    }

    public static function comment($a=false, $cmd = 'add') {
        switch ($cmd) {
            case 'add':
                $c = comment::post(array('app' => 'photos', 'itemID' => $a['itemID'], 'senderID' => $a['senderID'], 'comment' => $a['comment']));
                if ($c) {
                    $owner = db::query(sprintf("SELECT accountID FROM photos WHERE ID = %d LIMIT 1;", $a['itemID']), true);
                    $owner = profile::get(array('ID' => $owner->accountID));
                    $owner->status = profile::status($owner->accountID);
                    $sender = profile::get(array('ID' => $a['senderID']));
                    if ($owner->status == 'offline') {
                        //notification mail
                        $message = sprintf(_('You have a new comment on your %s photo $s from %s.')
                                        , '<a href="http://' . DOMAIN . '/photos/photo/' . $a['itemID'] . '">', '</a>'
                                        , '<a href="http://' . DOMAIN . '/' . $sender->link . '">' . $sender->fullname . '</a>');
                        notification::mail(array(
                                    'application' => 'photos',
                                    'sender' => $sender->ID,
                                    'recipient' => $owner->ID,
                                    'message' => $message
                                ));
                    }
                    notification::send(array(
                                'application' => 'photos',
                                'sender' => $sender->ID,
                                'recipient' => $owner->ID,
                                'item' => $a['itemID'],
                                'notification' => 'photo'
                            ));

                    return common::result(200, _('Your data has been saved... You are redirecting...'), null, '/photos/photo/' . $a['itemID'], true);
                }
                break;
        }
    }

    public static function notification($ID, $sender, $item = null) {
        $notification = array(
            'photo' => sprintf(_('%s commented on your %sphoto%s.')
                    , '<a href="http://' . DOMAIN . $sender->url . '">' . $sender->fullname . '</a>'
                    , '<a href="http://' . DOMAIN . '/photos/photo/' . $item . '">', '</a>')
        );
        return $notification[$ID];
    }

}

?>